package com.sdemo.common.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.sdemo.common.globals.Globals;
import com.sdemo.modules.sys.mapper.UserMapper;
import com.sdemo.modules.sys.model.Menu;
import com.sdemo.modules.sys.model.User;
import com.sdemo.modules.sys.model.UserRoleMenuData;
import com.sdemo.modules.sys.service.impl.RoleServiceImpl;
import com.sdemo.utils.jedis.MyJedis;

public class ShiroRealm extends AuthorizingRealm {
	private static final Logger logger = LoggerFactory.getLogger(ShiroRealm.class);
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RoleServiceImpl roleServiceImpl; 
	
	private MyJedis myJedis = MyJedis.getInstance();
	
	
    

    /**
     * 获取身份验证信息
     * Shiro中，最终是通过 Realm 来获取应用程序中的用户、角色及权限信息的。
     *
     * @param authenticationToken 用户身份信息 token
     * @return 返回封装了用户信息的 AuthenticationInfo 实例
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    	logger.info("————身份认证方法————");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 从数据库获取对应用户名密码的用户
        //String password = "e10adc3949ba59abbe56e057f20f883e";//userMapper.getPassword(token.getUsername());
        User user = userMapper.selectByUsername(token.getUsername());
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

    /**
     * 获取授权信息
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("————权限认证————");
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        
        List<Menu> list = null;
        String userauthJson = myJedis.hget(Globals.redis_userauth_key, Globals.redis_userid_key.concat(String.valueOf(user.getUserId())));
        if(null!=userauthJson && !"".equals(userauthJson) && userauthJson.length()>0){
        	UserRoleMenuData urmd  = JSONObject.parseObject(userauthJson, UserRoleMenuData.class);
        	list = urmd.getData();
        }else{
        	list = roleServiceImpl.queryAuthByRoleid(user.getUserId());
        	UserRoleMenuData urmd = new UserRoleMenuData();
        	urmd.setUserId(user.getUserId());
        	urmd.setData(list);
        	
        	String json = JSONObject.toJSONString(urmd);
            myJedis.hset(Globals.redis_userauth_key, Globals.redis_userid_key.concat(String.valueOf(user.getUserId())),json);
        }        
        Set<String> set = new HashSet<>();
        for(int i = 0 ; i < list.size(); i++){
        	 set.add(list.get(i).getAuthvalue());
        }
        info.setStringPermissions(set);
        return info;
    }

}
